/*
 * 五子棋游戏 - 坚果派
 * Gomoku Game by NutPi
 */

// 游戏状态管理
const GomokuGame = {
    // 棋盘配置
    BOARD_SIZE: 15,           // 棋盘大小 15x15
    CELL_SIZE: 30,            // 每个格子的大小
    PADDING: 15,              // 边距
    
    // 游戏状态
    board: [],                // 棋盘数组
    currentPlayer: 'black',   // 当前玩家 'black' 或 'white'
    gameOver: false,          // 游戏是否结束
    moveHistory: [],          // 移动历史（用于悔棋）
    
    // 得分
    scores: {
        black: 0,
        white: 0
    },
    
    // Canvas 相关
    canvas: null,
    ctx: null,
    
    // 初始化游戏
    init: function() {
        console.log('五子棋游戏初始化...');
        
        // 获取 Canvas 元素
        this.canvas = document.getElementById('gameBoard');
        if (!this.canvas) {
            console.error('Canvas 元素未找到');
            return;
        }
        
        this.ctx = this.canvas.getContext('2d');
        
        // 调整 Canvas 大小适应屏幕
        this.resizeCanvas();
        
        // 初始化棋盘
        this.initBoard();
        
        // 绘制棋盘
        this.drawBoard();
        
        // 绑定事件
        this.bindEvents();
        
        // 加载历史分数
        this.loadScores();
        
        console.log('游戏初始化完成');
    },
    
    // 调整 Canvas 大小
    resizeCanvas: function() {
        const container = document.querySelector('.board-container');
        const maxWidth = container.clientWidth - 20;
        const maxHeight = window.innerHeight * 0.5;
        const size = Math.min(maxWidth, maxHeight, 450);
        
        this.canvas.width = size;
        this.canvas.height = size;
        
        // 重新计算格子大小
        this.CELL_SIZE = (size - this.PADDING * 2) / (this.BOARD_SIZE - 1);
        
        console.log(`Canvas 尺寸: ${size}x${size}, 格子大小: ${this.CELL_SIZE}`);
    },
    
    // 初始化棋盘数组
    initBoard: function() {
        this.board = [];
        for (let i = 0; i < this.BOARD_SIZE; i++) {
            this.board[i] = [];
            for (let j = 0; j < this.BOARD_SIZE; j++) {
                this.board[i][j] = null;
            }
        }
        this.currentPlayer = 'black';
        this.gameOver = false;
        this.moveHistory = [];
        this.updateUI();
    },
    
    // 绘制棋盘
    drawBoard: function() {
        const ctx = this.ctx;
        const size = this.canvas.width;
        
        // 清空画布
        ctx.fillStyle = '#DEB887';
        ctx.fillRect(0, 0, size, size);
        
        // 绘制网格线
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 1;
        
        for (let i = 0; i < this.BOARD_SIZE; i++) {
            // 垂直线
            ctx.beginPath();
            ctx.moveTo(this.PADDING + i * this.CELL_SIZE, this.PADDING);
            ctx.lineTo(this.PADDING + i * this.CELL_SIZE, size - this.PADDING);
            ctx.stroke();
            
            // 水平线
            ctx.beginPath();
            ctx.moveTo(this.PADDING, this.PADDING + i * this.CELL_SIZE);
            ctx.lineTo(size - this.PADDING, this.PADDING + i * this.CELL_SIZE);
            ctx.stroke();
        }
        
        // 绘制星位（天元和四个角的星位）
        this.drawStar(7, 7);   // 天元
        this.drawStar(3, 3);   // 左上
        this.drawStar(3, 11);  // 右上
        this.drawStar(11, 3);  // 左下
        this.drawStar(11, 11); // 右下
        
        // 绘制已下的棋子
        this.drawPieces();
    },
    
    // 绘制星位点
    drawStar: function(row, col) {
        const x = this.PADDING + col * this.CELL_SIZE;
        const y = this.PADDING + row * this.CELL_SIZE;
        
        this.ctx.fillStyle = '#000000';
        this.ctx.beginPath();
        this.ctx.arc(x, y, 3, 0, 2 * Math.PI);
        this.ctx.fill();
    },
    
    // 绘制所有棋子
    drawPieces: function() {
        for (let i = 0; i < this.BOARD_SIZE; i++) {
            for (let j = 0; j < this.BOARD_SIZE; j++) {
                if (this.board[i][j]) {
                    this.drawPiece(i, j, this.board[i][j]);
                }
            }
        }
        
        // 标记最后一步
        if (this.moveHistory.length > 0) {
            const lastMove = this.moveHistory[this.moveHistory.length - 1];
            this.markLastMove(lastMove.row, lastMove.col);
        }
    },
    
    // 绘制单个棋子
    drawPiece: function(row, col, color) {
        const x = this.PADDING + col * this.CELL_SIZE;
        const y = this.PADDING + row * this.CELL_SIZE;
        const radius = this.CELL_SIZE * 0.4;
        
        const ctx = this.ctx;
        
        // 绘制棋子阴影
        ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
        ctx.shadowBlur = 5;
        ctx.shadowOffsetX = 2;
        ctx.shadowOffsetY = 2;
        
        // 绘制棋子
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, 2 * Math.PI);
        
        if (color === 'black') {
            const gradient = ctx.createRadialGradient(x - 2, y - 2, 0, x, y, radius);
            gradient.addColorStop(0, '#666');
            gradient.addColorStop(1, '#000');
            ctx.fillStyle = gradient;
        } else {
            const gradient = ctx.createRadialGradient(x - 2, y - 2, 0, x, y, radius);
            gradient.addColorStop(0, '#fff');
            gradient.addColorStop(1, '#ddd');
            ctx.fillStyle = gradient;
        }
        
        ctx.fill();
        
        // 绘制棋子边框
        ctx.shadowColor = 'transparent';
        ctx.strokeStyle = color === 'black' ? '#000' : '#999';
        ctx.lineWidth = 1;
        ctx.stroke();
    },
    
    // 标记最后一步
    markLastMove: function(row, col) {
        const x = this.PADDING + col * this.CELL_SIZE;
        const y = this.PADDING + row * this.CELL_SIZE;
        
        this.ctx.strokeStyle = '#FF0000';
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.arc(x, y, 5, 0, 2 * Math.PI);
        this.ctx.stroke();
    },
    
    // 绑定事件
    bindEvents: function() {
        // Canvas 点击事件
        this.canvas.addEventListener('click', (e) => this.handleClick(e));
        
        // 重新开始按钮
        document.getElementById('restartBtn').addEventListener('click', () => {
            this.restart();
        });
        
        // 悔棋按钮
        document.getElementById('undoBtn').addEventListener('click', () => {
            this.undo();
        });
        
        // 规则按钮
        document.getElementById('rulesBtn').addEventListener('click', () => {
            this.showRulesModal();
        });
        
        // 再来一局按钮
        document.getElementById('playAgainBtn').addEventListener('click', () => {
            this.closeWinModal();
            this.restart();
        });
        
        // 关闭规则弹窗
        const closeButtons = document.querySelectorAll('.close, .close-modal');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                this.closeRulesModal();
            });
        });
        
        // 窗口大小改变时重新绘制
        window.addEventListener('resize', () => {
            this.resizeCanvas();
            this.drawBoard();
        });
    },
    
    // 处理点击事件
    handleClick: function(e) {
        if (this.gameOver) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 转换为棋盘坐标
        const col = Math.round((x - this.PADDING) / this.CELL_SIZE);
        const row = Math.round((y - this.PADDING) / this.CELL_SIZE);
        
        // 检查坐标是否有效
        if (row < 0 || row >= this.BOARD_SIZE || col < 0 || col >= this.BOARD_SIZE) {
            return;
        }
        
        // 检查该位置是否已有棋子
        if (this.board[row][col]) {
            this.showMessage('该位置已有棋子');
            return;
        }
        
        // 下棋
        this.makeMove(row, col);
    },
    
    // 下棋
    makeMove: function(row, col) {
        // 记录移动
        this.board[row][col] = this.currentPlayer;
        this.moveHistory.push({
            row: row,
            col: col,
            player: this.currentPlayer
        });
        
        // 重绘棋盘
        this.drawBoard();
        
        // 检查是否获胜
        if (this.checkWin(row, col)) {
            this.handleWin();
            return;
        }
        
        // 检查是否平局
        if (this.moveHistory.length === this.BOARD_SIZE * this.BOARD_SIZE) {
            this.handleDraw();
            return;
        }
        
        // 切换玩家
        this.currentPlayer = this.currentPlayer === 'black' ? 'white' : 'black';
        this.updateUI();
    },
    
    // 检查是否获胜
    checkWin: function(row, col) {
        const directions = [
            [[0, 1], [0, -1]],   // 水平
            [[1, 0], [-1, 0]],   // 垂直
            [[1, 1], [-1, -1]],  // 左上-右下
            [[1, -1], [-1, 1]]   // 右上-左下
        ];
        
        for (let dir of directions) {
            let count = 1; // 当前棋子
            
            // 检查两个方向
            for (let [dx, dy] of dir) {
                let r = row + dx;
                let c = col + dy;
                
                while (r >= 0 && r < this.BOARD_SIZE && 
                       c >= 0 && c < this.BOARD_SIZE && 
                       this.board[r][c] === this.currentPlayer) {
                    count++;
                    r += dx;
                    c += dy;
                }
            }
            
            if (count >= 5) {
                return true;
            }
        }
        
        return false;
    },
    
    // 处理获胜
    handleWin: function() {
        this.gameOver = true;
        
        // 更新得分
        this.scores[this.currentPlayer]++;
        this.saveScores();
        this.updateUI();
        
        // 显示获胜弹窗
        setTimeout(() => {
            this.showWinModal();
        }, 300);
    },
    
    // 处理平局
    handleDraw: function() {
        this.gameOver = true;
        document.getElementById('gameStatus').textContent = '平局！';
        alert('平局！棋盘已满，没有人获胜。');
    },
    
    // 悔棋
    undo: function() {
        if (this.moveHistory.length === 0) {
            this.showMessage('无法悔棋');
            return;
        }
        
        if (this.gameOver) {
            this.showMessage('游戏已结束，无法悔棋');
            return;
        }
        
        // 撤销最后一步
        const lastMove = this.moveHistory.pop();
        this.board[lastMove.row][lastMove.col] = null;
        
        // 切换回上一个玩家
        this.currentPlayer = lastMove.player;
        
        // 重绘棋盘
        this.drawBoard();
        this.updateUI();
        
        this.showMessage('已悔棋');
    },
    
    // 重新开始
    restart: function() {
        if (this.moveHistory.length > 0 && !this.gameOver) {
            if (!confirm('游戏进行中，确定要重新开始吗？')) {
                return;
            }
        }
        
        this.initBoard();
        this.drawBoard();
        this.showMessage('新游戏开始');
    },
    
    // 更新 UI
    updateUI: function() {
        const playerElement = document.getElementById('currentPlayer');
        const statusElement = document.getElementById('gameStatus');
        
        if (this.gameOver) {
            const winner = this.currentPlayer === 'black' ? '⚫ 黑方' : '⚪ 白方';
            playerElement.textContent = winner;
            statusElement.textContent = '🏆 游戏结束';
            statusElement.style.color = '#4CAF50';
        } else {
            playerElement.textContent = this.currentPlayer === 'black' ? '⚫ 黑方' : '⚪ 白方';
            playerElement.className = 'player ' + this.currentPlayer;
            statusElement.textContent = '游戏进行中';
            statusElement.style.color = '#666';
        }
        
        // 更新得分
        document.getElementById('blackScore').textContent = this.scores.black;
        document.getElementById('whiteScore').textContent = this.scores.white;
        
        // 更新悔棋按钮状态
        document.getElementById('undoBtn').disabled = 
            this.moveHistory.length === 0 || this.gameOver;
    },
    
    // 显示消息
    showMessage: function(message) {
        const statusElement = document.getElementById('gameStatus');
        const originalText = statusElement.textContent;
        const originalColor = statusElement.style.color;
        
        statusElement.textContent = message;
        statusElement.style.color = '#FF9800';
        
        setTimeout(() => {
            if (!this.gameOver) {
                statusElement.textContent = originalText;
                statusElement.style.color = originalColor;
            }
        }, 2000);
    },
    
    // 显示规则弹窗
    showRulesModal: function() {
        document.getElementById('rulesModal').style.display = 'flex';
    },
    
    // 关闭规则弹窗
    closeRulesModal: function() {
        document.getElementById('rulesModal').style.display = 'none';
    },
    
    // 显示获胜弹窗
    showWinModal: function() {
        const modal = document.getElementById('winModal');
        const title = document.getElementById('winTitle');
        const message = document.getElementById('winMessage');
        
        const winner = this.currentPlayer === 'black' ? '⚫ 黑方' : '⚪ 白方';
        title.textContent = '🎉 ' + winner + ' 获胜！';
        message.textContent = `恭喜 ${winner} 获得胜利！\n当前比分：黑方 ${this.scores.black} : ${this.scores.white} 白方`;
        
        modal.style.display = 'flex';
    },
    
    // 关闭获胜弹窗
    closeWinModal: function() {
        document.getElementById('winModal').style.display = 'none';
    },
    
    // 保存得分
    saveScores: function() {
        try {
            localStorage.setItem('gomoku_scores', JSON.stringify(this.scores));
        } catch (e) {
            console.log('无法保存得分', e);
        }
    },
    
    // 加载得分
    loadScores: function() {
        try {
            const saved = localStorage.getItem('gomoku_scores');
            if (saved) {
                this.scores = JSON.parse(saved);
                this.updateUI();
            }
        } catch (e) {
            console.log('无法加载得分', e);
        }
    }
};

// Cordova 设备就绪事件
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    
    // 显示就绪指示器
    const indicator = document.getElementById('deviceready');
    if (indicator) {
        indicator.style.opacity = '1';
        setTimeout(() => {
            indicator.style.opacity = '0';
        }, 2000);
    }
    
    // 初始化游戏
    initGame();
}

// 初始化游戏（在 DOM 加载完成后或 deviceready 后）
function initGame() {
    console.log('开始初始化五子棋游戏...');
    
    // 确保 DOM 已加载
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            GomokuGame.init();
        });
    } else {
        GomokuGame.init();
    }
}

// 如果不在 Cordova 环境中，直接初始化
if (!window.cordova) {
    console.log('非 Cordova 环境，直接初始化游戏');
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            GomokuGame.init();
        });
    } else {
        GomokuGame.init();
    }
}
